package chapter14;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.*;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/21 16:01
 */
public class CsvTest {
    public static void main(String[] args) {
        String fileName = "d:\\student.csv";
//        testWrite(fileName);
        testRead(fileName);
    }

    private static void testWrite(final String fileName) {
        try (CSVPrinter printer = new CSVPrinter(new FileWriter(fileName), CSVFormat.DEFAULT)) {
            printer.printRecord("老马", 18, "看电影，看书，听音乐");
            printer.printRecord("小马", 16, "乐高，赛车");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void testRead(String fileName) {
        CSVFormat format = CSVFormat.newFormat(',')
                .withQuote('"').withNullString("N/A")
                .withIgnoreEmptyLines(true);

        try (Reader reader = new FileReader(fileName)) {
            for (CSVRecord record : format.parse(reader)) {
                int fieldNum = record.size();
                for (int i = 0; i < fieldNum; i++) {
                    System.out.println(record.get(i) + " ");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
